from django.contrib import admin
from django.contrib.admin.sites import NotRegistered
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models import signals
from django.http import HttpResponseRedirect
from django.templatetags.image_helpers import ImagePlaceholderNode

from pages.models import Page
from pages.admin import PageAdmin
from pages.models import Content
from pages.utils import get_placeholders

from pages_images_extension.models import Image

class PageAdminImagePlaceholderExtension(PageAdmin):
    ''' Override the save_model method to ensure an image is
        available to all placeholders. Additionally, add the image's
        id to the placeholder '''

    def save_model(self, request, obj, form, change, *args, **kwargs):
        (super(PageAdminImagePlaceholderExtension, self)
            .save_model(request, obj, form, change, *args, **kwargs))
        language = form.cleaned_data['language']
        placeholders = get_placeholders(obj.get_template())
        for placeholder in placeholders:
            if isinstance(placeholder, ImagePlaceholderNode):
                content = Content.objects.filter(page=obj,
                    language=language,
                    type=placeholder.name).latest()
                image = Image.objects.get_or_create(page = obj,
                    placeholder_name = placeholder.name)[0]
                form.cleaned_data[placeholder.name] = image.id
                content.body = image.id
                content.save()

class ImageAdmin(admin.ModelAdmin):
    ''' On save, redirect to the Page which the Image is placed on '''
    def change_view(self, request, object_id, *args, **kwargs):
        redirect_to = super(ImageAdmin, self).change_view(request, object_id, *args, **kwargs)

        if request.method == 'POST':
            image = Image.objects.get(id=object_id)
            content_type = ContentType.objects.get_for_model(Page)
            new_admin_url = reverse('admin:%s_%s_change'
                % (content_type.app_label, content_type.model),
                args=[image.page.id]) 
            redirect_to = HttpResponseRedirect(new_admin_url)
        return redirect_to

admin.site.register(Image, ImageAdmin)
try:
    admin.site.unregister(Page)
except NotRegistered:
    pass
admin.site.register(Page, PageAdminImagePlaceholderExtension)
